<?php

namespace app\admin\controller\tasks;

use app\common\controller\Backend;
use app\admin\model\AuthDepartment;
use fast\Tree;
use PHPExcel_IOFactory;
use app\admin\model\finance\extract\Week;
/**
 * 财务提成_周管理
 *
 * @icon fa fa-circle-o
 */
class Task extends Backend
{
	//当前是否为关联查询
    protected $relationSearch = true;
    protected $searchFields = 'task.id,task.name,task.userid,admin.username';
    /**
     * Week模型对象
     * @var \app\admin\model\finance\extract\Week
     */
    protected $model_week = null;
    protected $model_task = null;
    protected $Task_1 = null;
    protected $Task_2 = null;

    public function _initialize(){
        parent::_initialize();
        $this->model_week = new \app\admin\model\finance\extract\Week;
        $this->model_task = new \app\admin\model\finance\extract\Task;
        $this->Task_1 = new \app\admin\model\finance\extract\taskOut;
        $this->Task_2 = new \app\admin\model\integral\Taskbook;
        $this->TeacherModel = new \app\admin\model\integral\Teachertel;
        $this->Samplebook = new \app\admin\model\integral\Samplebook;
        $this->bookstoreModel = new \app\admin\model\integral\Bookstore;
        $this->School = new \app\admin\model\finance\extract\School;
    		$dept = GetBaseInfo('Dept');
    		$groupList = collection(AuthDepartment::field('*,parentid as pid')->where('id','in',''.implode(',',$dept).'')->whereOr('parentid','in',''.implode(',',$dept).'')->select())->toArray();
            Tree::instance()->init($groupList);
    		//权限
    		$this->RoleFinance = GetRoleFinance('week');

        $groupdata = [];
    		$result = [];
  		  if(!empty($this->RoleFinance['role'])){
  			$groups = $this->auth->getGroups();
  			$userid = \think\Session::get('admin')['userid'];
  			$temp = [];
  			foreach (explode(',',$this->RoleFinance['role']) as $m => $n){
  				$childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(2));
  				if($n == 2){
  					foreach ($childlist as $k => $v){
  					   if(ValueExists($dept,$v['id'])){
  							$kee = TableListSqlQuery('Field'," `parentid` = '".$v['id']."' ",'id','hdyj_auth_department');
  							$kee = implode(',',array_column($kee,'id'));
  							$temp[$kee] = $v['name'];
  							unset($kee);
  					   }else{
  						   $temp[$v['id']] = $v['name'];
  					   }
  					}
  				}else{
  					foreach ($childlist as $k => $v){	
  					  if(ValueExists($dept,$v['id'])){
  							if($v['id'] == $n || $v['parentid'] == $n) {
  								$kee = TableListSqlQuery('Field'," `parentid` = '".$v['id']."' ",'id','hdyj_auth_department');
  								$kee = implode(',',array_column($kee,'id'));
  								$temp[$kee] = $v['name'];
  								unset($kee);
  							}
  					   }else{
  						  if($v['id'] == $n || $v['parentid'] == $n) $temp[$v['id']] = $v['name'];
  					   }
  					}
  				}
  			}    
		    	$groupdata = $temp;
        }
        $this->loadlang('finance.extract.week');
        $this->view->assign('groupdata', $groupdata);
        $this->view->assign("statusList", $this->model_week->getStatusList());
        $this->view->assign("TaskstatusList", $this->Task_1->getStatusList());
    		$this->view->assign("divisionMethodList", $this->model_week->getDivisionMethodList());
    		$this->view->assign("divisionMethodRoundList", $this->model_week->getDivisionMethodRoundList());
    		$this->view->assign("typeList", $this->model_task->getTypeList());
    		$this->view->assign("Generate_Week", \think\Config::get('finance.Generate_Week'));
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index(){

       if ($this->request->isAjax()) {
	      
	        //设置过滤方法
	        $this->request->filter(['strip_tags']);
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
          	//任务是否删除
            $fi_where = " `task`.`delete_status` = 1 and ";
			       $fi_where .= $this->RoleFinance['where'];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model_task
                    ->with(['week','admin'])
                    ->where($where)
                    ->where($fi_where)
                    ->order($sort, $order)
                   // ->group('week.start_time,task.type')
                    ->count();
            $list = $this->model_task
                    ->with(['week','admin'])
                    ->where($where)
                    ->where($fi_where)
                    ->order($sort, $order)
                    //->group('week.start_time,task.type')
                    ->limit($offset, $limit)
                    ->select();
         // print_r($this->model_task->getLastSql());die;
            foreach ($list as $row) {
                $row->visible(['userid','id','extract_week','name','type','createtime','week','admin']);
                $row->getRelation('week')->visible(['start_time','end_time','department','status','week']);
				        $row->getRelation('admin')->visible(['username']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 提交审核
     */
    public function check($type = NULL,$task_id=NULL,$ids = NULL){ 
        if($type == 1){
          $model = $this->Task_1;
        }else{
          $model = $this->Task_2;
        }
        if ($ids) {
            $pk = $model->getPk();
    
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $model->where($pk, 'in', $ids)->select();
            $count = 0;
            $params['status'] = 3;
            foreach ($list as $k => $v) {
              if($v->status == 1 || $v->status == 2){
                $count += $v->allowField(true)->save($params);
              }
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 审核任务
     */
    public function review($type = NULL,$id =NULL, $status = NULL){ 
        if(!empty($type)){
              if($type == 1){
                 $model = $this->Task_1;
                $row = $model->get($id);
                $row->userids = $row->runner;
                $week['regLevelList']=$this->School->getRegLevelList();
                $week['LevelList']=$this->School->getLevelList();
                $week['rankingLevelList']=$this->School->getRankingLevelList();
                $this->view->assign("week", $week);
                 $this->view->assign("diskList", $model->diskList());
              }else{
                $model = $this->Task_2;
                $row = $model->get($id);
                $teacher = $this->TeacherModel->where(['books_id'=>$id])->field('name,subject,number,tel,id')->select()->toArray();//获取老师信息
                $samplebook  = $this->Samplebook->where(['books_id'=>$id])->field('yiluntidian,yilunjiaoan')->find();//获取图书信息
                $bookstore = $this->bookstoreModel->where(['books_id'=>$id])->field('id,bookstore_name,boss,tel,control,discount,status')->select()->toArray();
                if($samplebook){
                    $samplebook['yiluntidian'] = json_decode($samplebook['yiluntidian'],true);
                    $samplebook['yilunjiaoan'] = json_decode($samplebook['yilunjiaoan'],true);
                }
                if($row['evaluation_summary']){
                    $row['evaluation_summary'] = json_decode($row['evaluation_summary'],true);
                }
                
                $this->view->assign("teacher", $teacher);
                $this->view->assign("samplebook", $samplebook);
                $this->view->assign("bookstore", $bookstore);
             }
             //周id
             $extract_week = TableField('Task','extract_week',$row->task_id);
             $this->view->assign("extract_week", $extract_week);
             if ($this->request->isPost()) {

                $params = [];
                 $review = $this->request->post("review/a");
                  if($status == 3 && $type == 1){
                    if(!$review['season_id']) $this->error('请选择场次');
                    $params['season_id'] = $review['season_id'];
                    $params['salesinfo'] = $review['salesinfo'];
                    $params['userinfo'] = $review['userinfo'];
                    $params['book_num'] = $review['book_num'];
                    $params['book_price'] = $review['book_price'];
                    $params['people_num'] = $review['people_num'];
                  }
             
                 if($check_status = GetStatusTasks($status,$review['check'])){
                  //判断等多个和跑人
                  if($status == 1 ){
                    $check_userids = array_diff(explode(',', $row->userids),explode(',', $row->check_userids));
                    if(count($check_userids)){
                      $params['check_userids'] = $row->check_userids ? $row->check_userids.','.\think\Session::get('admin')['userid'] : \think\Session::get('admin')['userid'];
                       $check_userids = array_diff(explode(',', $row->userids),explode(',', $params['check_userids']));
                      if(count($check_userids)){
                        $check_status = 3;
                      }
                    }
                   }
                    $params['status'] = $check_status;
                    $params['z_publish'] = \think\Session::get('admin')['userid'];
                    if($result =  $model->save($params,['id'=>$id])){
                      //审核记录
                      InstallNoteTasks($row,$review['check'],$review['desc']);
                      //成功就插入
                      if($check_status == 9 && $type == 1){
                          InstallSchoolTask($extract_week,$row);
                      }
                    }
                 }else{
                    $this->error('审核失败，请稍后重试');
                 }
                $this->success();
             }
             //print_r($row->sample);die;
            $this->view->assign("row", $row);
            $status_arr = ['3','4','5'];
            //财务审核-负责人审核-客户管理部审核
          if(in_array($status, $status_arr) && $type == 1){
            //处理外联信息
            if(empty($row->userinfo)){
               $row->userinfo = array_merge($row->runner?explode(',', $row->runner):[],[TableField('Task','userid',$row->task_id)]);
               $row->userinfo = json_encode(array_values(array_column(array_map(function($vss){
                  return [
                      'userid'=>$vss,
                      'username'=>TableField('Admin','username',$vss,'userid'),
                      'proportion'=>0,
                  ];
               }, $row->userinfo),null,'userid')));
             }
             //处理销售信息
            if($row->salesinfo){ 
             if(count($salesinfo = array_column(ObjectArray(json_decode($row->salesinfo)), 'value','key'))){
                $row->salesinfo = json_encode($salesinfo);
              }elseif(count($salesinfo = ObjectArray(json_decode($row->salesinfo)))){
                $row->salesinfo = json_encode($salesinfo);
              }
            }else{
              $row->salesinfo = json_encode(GetBaseInfo('SalesPrice2'));
            }
          
            $this->view->assign("userinfo", $row->userinfo);
            $this->view->assign("salesinfo", $row->salesinfo);
            $this->view->assign("disabled", $status!=3?'disabled':'');
            //print_r(TableField('Task','extract_week',$row->task_id));die;
            return $this->view->fetch('public_review_status'.$type);
          }else{
            return $this->view->fetch('public_review_'.$type);
          }
        }else{
          //任务权限状态
          $TaskRoleStatus =  GetRoleTasks();
          if ($this->request->isAjax()) {
            //设置过滤方法
            $this->request->filter(['strip_tags']);
              //如果发送的来源是Selectpage，则转发到Selectpage
              if ($this->request->request('keyField'))
              {
                  return $this->selectpage();
              }
              //任务是否删除
               $fi_where = " `task`.`delete_status` = 1 and ";
               //判断合跑人权限
               if(AdminAuth("tasks/task/review_1")){
                  //权限
                  $this->RoleFinance = GetRoleFinance('task');
               }else{
                  $this->RoleFinance = GetRoleFinance('wweek');
               }
               //任务单相关权限
               $fi_where .= $this->RoleFinance['where'];
               $fi_where .= " and (`taskotreach`.task_id > 0 or `taskbook`.task_id > 0 ) and ( find_in_set(taskotreach.`status`,'".implode(',', $TaskRoleStatus)."')>0 or find_in_set(taskbook.`status`,'".implode(',', $TaskRoleStatus)."')>0 ) ";
              list($where, $sort, $order, $offset, $limit) = $this->buildparams();
              $total = $this->model_task
                      ->with(['week','admin','taskotreach','taskbook'])
                      ->where($fi_where)
                      ->where($where)
                      ->order($sort, $order)
                      ->count();
              $list = $this->model_task
                      ->with(['week','admin','taskotreach','taskbook'])
                      ->where($fi_where)
                      ->where($where)
                      ->order($sort, $order)
                      ->limit($offset, $limit)
                      ->select();  
              foreach ($list as $row) {
                  $row->visible(['userid','id','extract_week','name','type','createtime','week','admin','taskotreach','taskbook']);
                  $row->getRelation('week')->visible(['start_time','end_time','department','status','week']);
                  $row->getRelation('admin')->visible(['username']);
                  $row->getRelation('taskotreach')->visible(['id','school_id','status','createtime','updatetime']);
                  $row->getRelation('taskbook')->visible(['id','school_id','status','createtime','updatetime']);
             
              }
           // print_r($this->model_task->getLastSql());die;
              $list = collection($list)->toArray();
              $result = array("total" => $total, "rows" => $list);
              return json($result);
          }
           //$this->view->assign("TaskstatusList", $this->Task_1->getStatusList());
          $this->view->assign("TaskRoleStatus", GetRoleTasks());
          return $this->view->fetch();
        }
    }
   

	
  
}
